﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lamex.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraCharts;
using DevExpress.Charts.Model;

namespace Lamex.Library.UserCotrolUI
{
    public partial class FrmProductQualityControlUI : UserControl
    {
        public FrmProductQualityControlUI()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 设置站别名称11
        /// </summary>
        /// <param name="ProcessName"></param>
       
        public void ShowProcessList(string ProcessCode,int iStandTime,string UserName)
        {
            try
            {
                if (string.IsNullOrEmpty(ProcessCode))
                {
                    XtraMessageBox.Show("没有输入工序号");
                    return;
                }
                DataTable dtItme = BaseBuildSql.GetDataTableBySql(@" select a.* from  [dbo].[HR_Work_ShiftRec]  a 
 join (select top 1* from  [HR_Station_Info]  where STATION_NAME='" + UserName + @"') b on b.DEPARTMENT=a.DEPARTMENT
 where   a.EFFECTIVE_DATE<  CONVERT(nvarchar(10),GETDATE(),120) and CONVERT(nvarchar(10),GETDATE(),120)<CONVERT(nvarchar(10), a. EXPIRY_DATE,120)
                                                                ");
                string time = DateTime.Now.ToString("yyyy -MM-dd");
                string startday = DateTime.Now.ToString("yyyy-MM-dd");
                string timestart1 = "";
                string timestart2 = "";
                string timestart3 = "";
                string timesEnd1 = "";
                string timesEnd2 = "";
                string timesEnd3 = "";
                string[] strArrayTime = dtItme.Rows[0]["T1_START"].ToString().Split(':');

                if (dtItme.Rows.Count != 0)
                {
                    time = time + " " + dtItme.Rows[0]["T1_START"].ToString();
                    timestart1 = startday + " " + dtItme.Rows[0]["T1_START"].ToString();
                    timestart2 = startday + " " + dtItme.Rows[0]["T2_START"].ToString();
                    timestart3 = startday + " " + dtItme.Rows[0]["T3_START"].ToString();
                    timesEnd1 = startday + " " + dtItme.Rows[0]["T1_END"].ToString();
                    timesEnd2 = startday + " " + dtItme.Rows[0]["T2_END"].ToString();
                    timesEnd3 = startday + " " + dtItme.Rows[0]["T3_END"].ToString();

                }
                else
                {
                    XtraMessageBox.Show("没有员工排班表");
                    return;
                }
                DateTime startTime1 = Convert.ToDateTime(timestart1);
                DateTime startTime2 = Convert.ToDateTime(timestart2);
                DateTime startTime3 = Convert.ToDateTime(timestart3);

                DateTime endTime1 = Convert.ToDateTime(timesEnd1);
                DateTime endTime2 = Convert.ToDateTime(timesEnd2);
                DateTime endTime3 = Convert.ToDateTime(timesEnd3);
                DateTime startTime = DateTime.Now;
                decimal hour1 = 0;
                decimal hour2 = 0;
                decimal hour3 = 0;
                #region"计算当前时间的数据值"
                if (endTime1 > startTime)
                {
                    TimeSpan span = startTime.Subtract(startTime1);
                    hour1 = Convert.ToDecimal(span.Hours) + Convert.ToDecimal(span.Minutes) / 60;
                }
                else if (endTime1 < startTime && startTime2 > startTime)
                {
                    TimeSpan span = endTime1.Subtract(startTime1);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (startTime2 < startTime && startTime < endTime2)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + startTime.Subtract(startTime2);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (endTime2 < startTime && startTime < startTime3)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (startTime3 < startTime && startTime < endTime3)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2) + startTime.Subtract(startTime3);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                else if (endTime3 < startTime)
                {
                    TimeSpan span = endTime1.Subtract(startTime1) + endTime2.Subtract(startTime2) + endTime3.Subtract(startTime3);
                    hour1 = Convert.ToDecimal(span.Hours) + Math.Round(Convert.ToDecimal(span.Minutes) / 60, 1);
                }
                #endregion


                //DataTable dataTimeList = BaseBuildSql.GetDataTableBySql(@"select top 1* from [dbo].[HR_Scan_Record] where 1=1 
                //                                                        and CONVERT(nvarchar(10), SCAN_TIME, 120) = CONVERT(nvarchar(10), GETDATE(), 120)
                //                                                        and BARCODE = 'MES_MG00000' and SCANNER_NO='" + UserName + "';");
                //if (dataTimeList.Rows.Count == 0) return;
                //string startTimes = dataTimeList.Rows[0]["SCAN_TIME"].ToString();


                string local = UserName + "_09"; ;
                DataTable dtPass = BaseBuildSql.GetDataTableBySql(@" select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)  and STATION_NAME='"+ UserName + @"' group by CONVERT(nvarchar(6),BARCODE)
union all
select m.SCAN_QTY- case when isnull(n.SCAN_QTY,'')=''then 0 else n.SCAN_QTY end SCAN_QTY,m.MES_PD from (select sum(SCAN_QTY) SCAN_QTY,'MES_PD' as MES_PD from HR_Scan_Record  s
left join HR_Station_Info i on i.LOCATION_NAME=s.LOCATION_CODE
where i.LOCATION_CODE='"+ local + @"' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and s.STATION_NAME='" + UserName + @"'
group by i.LOCATION_CODE) m 
left join (select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE,'MES_PD' as MES_PD from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) group by CONVERT(nvarchar(6),BARCODE)
) n on n.MES_PD=m.MES_PD

                                                            ");
                if (dtPass.Rows.Count == 0)
                {
                    //XtraMessageBox.Show("扫描表还没有数据!");
                    return;
                }
                DataRow dr = dtPass.Select(" 1=1 and BARCODE='MES_PD'").FirstOrDefault();
                decimal quality = 0;
                if (dr != null)
                {
                    quality = decimal.Parse(dr["SCAN_QTY"].ToString()) / hour1;
                }



                //time  = Convert.ToDateTime(time).AddHours(1).ToString("yyyy-MM-dd HH");
                //time = time + ":00:00:000";

                DateTime dates = Convert.ToDateTime(time);
                string dateEnd = endTime3.ToString();



                List<string> lst = new List<string>();

                DataSet ds = null;
                if (strArrayTime[1] == "00")
                {
                    dates = dates.AddHours(1);
                    lst.Add(dates.ToString());
                    lst.Add(endTime3.AddHours(1).ToString());//晚上结束时间
                    lst.Add(UserName);
                    lst.Add(UserName+"_09");
                    ds = BaseBuildSql.GetProNameDataSet("P_GetProductQualityNew2", lst);
                }

                else
                {
                    dates = dates.AddHours(-1);
                    lst.Add(dates.ToString());
                    lst.Add(endTime3.AddHours(1).ToString());
                    lst.Add(UserName);
                    lst.Add(UserName + "_09");
                    ds = BaseBuildSql.GetProNameDataSet("P_GetProductQualitySource", lst);
                }

                DataTable dtUseTime = ds.Tables[0];//用时
                DataTable dtRestTime = ds.Tables[1];//休时





                ///同柱状显示不同颜色
                chartProductQualityUI.Series.Clear();
                Series seriesAuto = new Series("", ViewType.StackedBar);
                Series seriesAuto1 = new Series("", ViewType.StackedBar);

                foreach (DataRow drow in dtRestTime.Rows)
                {
                    SeriesPoint p = new SeriesPoint();

                    double[] d = new double[] { Convert.ToDouble(Math.Floor(double.Parse(drow["SCAN_QTY"].ToString()) / double.Parse(iStandTime.ToString())).ToString()) };
                    p.Values = d;

                    p.Argument = drow["TIMES"].ToString();
                    p.Color = Color.Gray;
                    seriesAuto.Points.Add(p);
                }

                foreach (DataRow drow in dtUseTime.Rows)
                {
                    SeriesPoint p = new SeriesPoint();
                    double[] d = new double[] { double.Parse(drow["SCAN_QTY"].ToString()) };
                    p.Values = d;
                    p.Argument = drow["TIMES"].ToString();
                    p.Color = Color.Blue;
                    seriesAuto1.Points.Add(p);
                }




                int maxQuality = 0;//计算最大值
                foreach (DataRow d in dtUseTime.Rows)
                {
                    if (int.Parse(d["SCAN_QTY"].ToString()) > maxQuality)
                        maxQuality = int.Parse(d["SCAN_QTY"].ToString());
                }
                //string ProcessName = "工人"+ ProcessCode;
                //chartProductQualityUI.Series.Clear();
                //seriesAuto.DataSource = dtProcess;


                //seriesAuto.ArgumentScaleType = ScaleType.Qualitative;
                //名称
                //seriesAuto.ArgumentDataMember = "TIMES";

                //seriesAuto.ValueScaleType = ScaleType.Numerical;
                //seriesAuto.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;

                //seriesAuto.Visible = false;
                //取值字段 
                //seriesAuto.ValueDataMembers.AddRange(new string[] { "SCAN_QTY" });
                //(seriesAuto.Label as PieSeriesLabel).Position = PieSeriesLabelPosition.Outside;
                //显示标项目名称和百分比数据
                //seriesAuto.PointOptions.PointView = PointView.ArgumentAndValues;
                //seriesAuto.PointOptions.ValueNumericOptions.Format = NumericFormat.General;



                //seriesAuto1.ArgumentDataMember = "TIMES";
                ////seriesAuto1.ValueScaleType = ScaleType.Numerical;
                ////seriesAuto1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;
                //seriesAuto1.ValueDataMembers.AddRange(new string[] { "SCAN_QTY" });
                seriesAuto1.PointOptions.ValueNumericOptions.Format = NumericFormat.General;

                seriesAuto1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据


                //ChartTitle autoTitle = new ChartTitle();
                //autoTitle.Text = "Hour";
                //chartHour.Titles.Clear();
                //chartHour.Titles.Add(autoTitle);
                this.chartProductQualityUI.Series.Add(seriesAuto);
                this.chartProductQualityUI.Series.Add(seriesAuto1);

                StackedBarSeriesLabel point = (StackedBarSeriesLabel)seriesAuto1.Label;
                point.Position = BarSeriesLabelPosition.TopInside;

                //foreach (DataRow d in dtProcess.Rows)
                //{
                //    d["SCAN_QTY"] = 5;
                //}
                //seriesAuto1.DataSource = dtProcess;
                //seriesAuto1.ArgumentDataMember = "TIMES";
                //seriesAuto1.ValueScaleType = ScaleType.Numerical;
                //seriesAuto1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;
                ////取值字段 
                //seriesAuto1.ValueDataMembers.AddRange(new string[] { "SCAN_QTY" });
                //seriesAuto1.PointOptions.ValueNumericOptions.Format = NumericFormat.General;

                //this.chartProductQualityUI.Series.Add(seriesAuto1);

                //chartProductQualityUI.Series[0].Points[0].Color = Color.SkyBlue;
                //chartProductQualityUI.Series[1].Points[0].Color = Color.Yellow;

                XYDiagram diagramhour = (XYDiagram)chartProductQualityUI.Diagram;
                diagramhour.AxisY.ConstantLines.Clear();
                //diagramhour.EnableAxisXScrolling = true;
                //diagramhour.EnableAxisXZooming = true;
                //diagramhour.EnableAxisYScrolling = true;
                //diagramhour.EnableAxisYZooming = true;
                diagramhour.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagramhour.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;
                diagramhour.AxisY.WholeRange.MaxValue = maxQuality * 1.2;
                diagramhour.AxisY.WholeRange.MinValue = 0;


                //diagramhour.AxisY.VisualRange.MinValue = iStandTime * 0.75;
                ////diagramhour.AxisY.VisualRange.MaxValue = 250;
                ////diagramhour.AxisY.VisualRange.SideMarginsValue = 10;
                //diagramhour.AxisY.WholeRange.MaxValue = 260;
                //diagramhour.AxisY.WholeRange.MinValue = 150;
                //diagramhour.AxisY.WholeRange.AlwaysShowZeroLevel = true;
                //diagramhour.AxisY.WholeRange.SideMarginsValue = 1;

                //diagramhour.AxisY.Logarithmic = true;
                //diagramhour.AxisY.LabelVisibilityMode = AxisLabelVisibilityMode.Default;
                //diagramhour.AxisY.LogarithmicBase=10;
                // diagramhour.AxisX.WholeRange.MinValue = 30;
                //diagramhour.AxisX.Interlaced = true;
                //diagramhour.AxisX.Label = 10
                //diagramhour.AxisX.WholeRange.MaxValue= 150;
                //diagramhour.AxisX.WholeRange.MinValue = 0;
                //diagramhour.AxisX.Logarithmic = true;
                //diagramhour.AxisX.LogarithmicBase = 5;

                ConstantLine constantLineligh = new ConstantLine(Math.Round(quality, 1).ToString() + "PC/H", Math.Round(quality, 1));

                //decimal iStander =  (3600 / decimal.Parse( iStandTime.ToString())) * quality;
                double second = 3600;
                double hh = 7.5;
                double hh1 = 8;
                double stander = Convert.ToDouble(iStandTime.ToString());
                double target = second / stander * hh / hh1;


                if (quality > Convert.ToDecimal((target).ToString()))
                {
                    constantLineligh.Color = Color.Green; //直线颜色
                    constantLineligh.Title.TextColor = Color.Green;   //直线文本字体颜色  
                }
                else
                {
                    constantLineligh.Color = Color.Red; //直线颜色
                    constantLineligh.Title.TextColor = Color.Red;   //直线文本字体颜色  
                }
                constantLineligh.Title.Visible = true;
                constantLineligh.ShowInLegend = false;
                diagramhour.AxisY.ConstantLines.Add(constantLineligh);

                ConstantLine constantLineligh1 = new ConstantLine("目标" + Math.Round(target, 1) + "PC/H", Math.Round(target, 1));
                //当前小时产量
                constantLineligh1.Color = Color.Green; //直线颜色
                constantLineligh1.Title.TextColor = Color.Green;   //直线文本字体颜色  
                constantLineligh1.Title.Alignment = ConstantLineTitleAlignment.Far;
                constantLineligh1.Title.Visible = true;
                constantLineligh1.ShowInLegend = false;

                diagramhour.AxisY.ConstantLines.Add(constantLineligh1);

                //ConstantLine constantLinelow = new ConstantLine((iStandTime * 0.75).ToString(), 150);
                //constantLinelow.Color = Color.AntiqueWhite; //直线颜色
                //constantLinelow.Title.TextColor = Color.Black;   //直线文本字体颜色    
                //constantLinelow.Title.Visible = true;
                //constantLinelow.ShowInLegend = false;
                //diagramhour.AxisY.ConstantLines.Add(constantLinelow);

                //ConstantLine constantLine2 = new ConstantLine("CT:" + iStandTime.ToString(), iStandTime);
                //constantLine2.Color = Color.Green; //直线颜色
                //constantLine2.Title.TextColor = Color.Green;   //直线文本字体颜色    
                //constantLine2.Title.Visible = true;
                //constantLine2.ShowInLegend = false;
                //diagramhour.AxisY.ConstantLines.Add(constantLine2);

                //ConstantLine constantLine3 = new ConstantLine((iStandTime * 1.05).ToString(), iStandTime * 1.05);
                //constantLine3.Color = Color.Red; //直线颜色
                //constantLine3.Title.TextColor = Color.Red;   //直线文本字体颜色    
                //constantLine3.Title.Visible = true;
                //constantLine3.ShowInLegend = false;
                //diagramhour.AxisY.ConstantLines.Add(constantLine3);

                //ConstantLine constantLine4 = new ConstantLine((iStandTime * 0.95).ToString(), iStandTime * 0.95);
                //constantLine4.Color = Color.Yellow; //直线颜色
                //constantLine4.Title.TextColor = Color.Yellow;   //直线文本字体颜色    
                //constantLine4.Title.Visible = true;
                //constantLine4.ShowInLegend = false;
                //diagramhour.AxisY.ConstantLines.Add(constantLine4);
                //diagramhour.AxisY.Title.Text = "";
                //diagramhour.AxisY.Title.Visible = false;
                //diagramhour.AxisY.Title.Alignment = StringAlignment.Center;
                //diagramhour.AxisY.Title.Antialiasing = true;
                //diagramhour.AxisY.Color = Color.Black;
                //diagramhour.AxisX.Color = Color.Black;
                //diagramhour.AxisX.Title.Text = "icount";
                //diagramhour.AxisX.Title.Visible = true;
                //diagramhour.AxisX.Title.Alignment = StringAlignment.Center;
                //diagramhour.AxisX.Title.Antialiasing = true;
                //横标题设置
                //chartProductQualityUI.Titles.Clear();
                //ChartTitle titles = new ChartTitle();            //声明标题
                //titles.Text = ProcessName;                            //名称
                //                                                      //titles.TextColor = System.Drawing.Color;   //颜色
                //titles.Indent = 1;                                //设置距离  值越小柱状图就越大
                //titles.Font = new Font("Tahoma", 12, FontStyle.Bold);            //设置字体
                //titles.Dock = ChartTitleDockStyle.Top;           //设置对齐方式
                //titles.Indent = 0;
                //titles.Alignment = StringAlignment.Center;       //居中对齐
                //chartProductQualityUI.Titles.Add(titles);                 //添加标题  
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+"quality");
            }

        }
    }
}
